# -*- coding: utf-8 -*-

import pymysql as pymysql

from app.core.config import Config
from app.core.core import Singleton
from app.core.log import Log


@Singleton
class Database:
    """
    配置文件操作类

    使用:
    db = Database()
    """

    def __init__(self):
        self._log = Log().init()
        self._config = Config().init()

        self._host = self._config.get("mysql", "host")
        self._username = self._config.get("mysql", "username")
        self._password = self._config.get("mysql", "password")
        self._port = self._config.getint("mysql", "port")
        self._database = self._config.get("mysql", "database")

        self.conn, self.cursor = self._get_database()

    def _get_database(self):
        """获取pymysql对象实例"""

        conn = pymysql.connect(host=self._host, port=self._port, user=self._username, password=self._password,
                               database=self._database)

        cursor = conn.cursor()

        return conn, cursor

    def __del__(self):
        self.conn.close()
        self._log.info("mysql is closed!")
